/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cgd;

import cdp.ObjetoPersistente;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Rodrigo
 */
public class DAOHibernateImpl <T extends ObjetoPersistente> implements DAO<T>{
    protected Session currentSession = HibernateUtil.getInstance().getCurrentSession();

    @Override
    public void salvar(T objeto) throws Exception {
        currentSession.beginTransaction();
        currentSession.save( objeto );        
        currentSession.getTransaction().commit();
        currentSession.clear();
        currentSession.flush();
    }

    @Override
    public void excluir(T objeto) throws Exception {
        currentSession.clear();
        currentSession.flush();
        currentSession.beginTransaction();
        currentSession.delete(objeto);
        currentSession.getTransaction().commit();
        currentSession.clear();
        currentSession.flush();
        
    }

    @Override
    public void alterar(T objeto) throws Exception {
        currentSession.clear();
        currentSession.flush();
        currentSession.beginTransaction();
        currentSession.update(objeto);
        currentSession.getTransaction().commit();
        currentSession.clear();
        currentSession.flush();
        
    }

    @Override
    public T obter(T objeto) throws Exception {
        currentSession.beginTransaction();
        currentSession.load(objeto, new Long(objeto.getId()));
        currentSession.getTransaction().commit();
        
        return objeto;
    }

    @Override
    public T obter(T objeto, long id) throws Exception {
        currentSession.beginTransaction();
        Query query = currentSession.createQuery(" from " + objeto.getClass().getSimpleName() + " where id" + "_" + objeto.getClass().getSimpleName() + " = " + id);
        objeto = (T)query.uniqueResult();
        currentSession.getTransaction().commit();
        
        return objeto;
    }

    @Override
    public List<T> obterTodos(T objeto) throws Exception {
        currentSession.beginTransaction();
        List result = currentSession.createQuery( "from " + objeto.getClass().getSimpleName()).list();
        currentSession.getTransaction().commit();
        
        return result;
    }  
}
